import Message from '@/miniprogram_npm/tdesign-miniprogram/message/index';

// 封装 wx.chooseMessageFile 为 Promise
const chooseFile = () => {
    return new Promise((resolve, reject) => {
        wx.chooseMessageFile({
            count: 1,
            type: 'file',
            success: (res) => resolve(res.tempFiles[0]),
            fail: (err) => reject(err)
        });
    });
};

// 封装 fs.readFile 为 Promise
const readFile = (filePath) => {
    const fs = wx.getFileSystemManager();
    return new Promise((resolve, reject) => {
        fs.readFile({
            filePath,
            success: (res) => resolve(res.data),
            fail: (err) => reject(err)
        });
    });
};

export const chooseMessageFile = async (suffixArray, size) => {
    try {
        const tempFile = await chooseFile();

        // 校验文件后缀
        const suffix = tempFile.name.split('.').pop();
        if (tempFile.type !== 'file' || !suffixArray.includes(suffix)) {
            throw new Error(`仅支持 ${suffixArray.join('\u3001')} 格式的文件`);
        }

        // 校验文件大小
        if (tempFile.size > size) {
            throw new Error(`文件大小不大于${size / 1000}MB`);
        }

        // 读取文件内容
        const fileData = await readFile(tempFile.path);
        return { tempFile, fileData };
    } catch (error) {
        throw error;
    }
};

export const textDecoder = (buffer) => {
    const uint8Array = new Uint8Array(buffer);
    return decodeURIComponent(escape(String.fromCharCode(...uint8Array)));
};
